package com.yict.csms.adminManage.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.yict.common.dao.impl.BaseDao;
import com.yict.csms.adminManage.dao.IContractorRankingDao;
import com.yict.csms.adminManage.entity.ContractorRanking;

/**
 * 
 * 
 * @author ryan.wang
 * 
 */
@Repository("contractorRankingDao")
public class ContractorRankingDaoImpl extends BaseDao<ContractorRanking, Long> implements IContractorRankingDao {

	@Override
	public boolean check(String flag, ContractorRanking contractorRanking, boolean saveOrUpdate){
		boolean bool = false;
		Map<String, Object> map = new HashMap<String, Object>();
		StringBuilder queryString = new StringBuilder("from ContractorRanking t where 1=1 and t.typeId.profeid = :typeId and ((t.startDate >=:startDate " +
				" and t.startDate <=:endDate) or (t.endDate >=:startDate and t.endDate <=:endDate))");
		map.put("typeId", contractorRanking.getTypeId().getProfeid());
		map.put("startDate", contractorRanking.getStartDate());
		map.put("endDate", contractorRanking.getEndDate());
		if(flag != null && flag.equals("ranking")) {
			queryString.append(" and t.ranking = :id");
			map.put("id", contractorRanking.getRanking());
		}
		if(flag != null && flag.equals("company")) {
			queryString.append(" and t.companyId.companyId = :id");
			map.put("id", contractorRanking.getCompanyId().getCompanyId());
		}
		if(!saveOrUpdate) {
			queryString.append(" and t.rankingId not in (:rankingId)");
			map.put("rankingId", contractorRanking.getRankingId());
		}
		try {
			Query query = this.getSession().createQuery(queryString.toString());
			query.setProperties(map);
			List<String> list = query.list();
			if(list != null && list.size() > 0) {
				bool = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bool;
	}

	@Override
	public Long findMaxRanking(Long typeId) {
		Long result = 1L;
		String queryString = "select max(t.ranking) from ContractorRanking t where 1=1 and t.typeId.profeid = :typeId ";
		try {
			Query query = this.getSession().createQuery(queryString);
			query.setParameter("typeId", typeId);
			List<Long> list = query.list();
			if (list != null && list.size() > 0) {
				result = list.get(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public List<ContractorRanking> verifyRanking(Long[] companyIds) {
		StringBuilder queryString = new StringBuilder("from ContractorRanking t where t.companyId.companyId in (:companyIds) ");
		Query query = this.getSession().createQuery(queryString.toString());
		query.setParameterList("companyIds", companyIds);
		return (List<ContractorRanking>) query.list();
	}
}
